import Router from 'koa-router';
import { ServiceStaff } from '../models/index.js';
import { Op } from 'sequelize';
import { User } from '../models/index.js';

const router = new Router({
  prefix: '/api/service-staff'
});

// 获取客服列表
router.get('/', async (ctx) => {
  try {
    const {
      page = 1,
      pageSize = 10,
      type,
      status,
      keyword,
      sortBy = 'createdAt',
      sortOrder = 'DESC'
    } = ctx.query;

    // 构建查询条件
    const where = {};
    if (type) {
      where.type = type;
    }
    if (status) {
      where.status = status;
    }
    if (keyword) {
      where[Op.or] = [
        { nickname: { [Op.like]: `%${keyword}%` } },
        { email: { [Op.like]: `%${keyword}%` } }
      ];
    }

    // 执行查询
    const { count, rows } = await ServiceStaff.findAndCountAll({
      where,
      order: [[sortBy, sortOrder]],
      limit: parseInt(pageSize),
      offset: (parseInt(page) - 1) * parseInt(pageSize)
    });

    ctx.body = {
      total: count,
      totalPages: Math.ceil(count / pageSize),
      currentPage: parseInt(page),
      pageSize: parseInt(pageSize),
      list: rows
    };
  } catch (error) {
    console.error('查询客服列表失败:', error);
    ctx.throw(500, '查询客服列表失败');
  }
});

// 获取指定客服信息
router.get('/:id', async (ctx) => {
  try {
    const { id } = ctx.params;
    const staff = await ServiceStaff.findByPk(id);
    
    if (!staff) {
      ctx.throw(404, '客服不存在');
    }
    
    ctx.body = staff;
  } catch (error) {
    console.error('查询客服信息失败:', error);
    ctx.throw(500, '查询客服信息失败');
  }
});

// 创建新客服
router.post('/', async (ctx) => {
  try {
    const { nickname, phone, type, description, email, userId } = ctx.request.body;
    
    // 验证必填字段
    if (!nickname || !type || !email) {
      ctx.throw(400, '昵称、类型和邮箱为必填项');
    }

    // 检查类型是否有效
    const validTypes = ['platform_admin', 'community_admin', 'community_service'];
    if (!validTypes.includes(type)) {
      ctx.throw(400, '无效的客服类型');
    }

    // 检查邮箱是否已注册
    const user = await User.findOne({
      where: { email }
    });

    if (!user) {
      ctx.throw(400, '该邮箱尚未注册用户账号');
    }

    // 检查邮箱是否已被其他客服使用
    const existingStaff = await ServiceStaff.findOne({
      where: { email }
    });

    if (existingStaff) {
      ctx.throw(400, '该邮箱已被其他客服使用');
    }

    // 检查userId是否已被使用
    if (userId) {
      const existingStaffWithUserId = await ServiceStaff.findOne({
        where: { userId }
      });

      if (existingStaffWithUserId) {
        ctx.throw(400, '该用户已经是客服了');
      }
    }

    // 如果没有提供userId，使用通过邮箱找到的用户id
    const actualUserId = userId || user.id;

    const staff = await ServiceStaff.create({
      nickname,
      phone,
      email,
      userId: actualUserId,
      type,
      description,
      status: 'active'
    });

    ctx.status = 201;
    ctx.body = staff;
  } catch (error) {
    console.error('创建客服失败:', error);
    ctx.throw(500, '创建客服失败');
  }
});

// 更新客服信息
router.put('/:id', async (ctx) => {
  try {
    const { id } = ctx.params;
    const updateData = { ...ctx.request.body };
    
    const staff = await ServiceStaff.findByPk(id);
    if (!staff) {
      ctx.throw(404, '客服不存在');
    }

    // 如果要更新类型，检查是否有效
    if (updateData.type) {
      const validTypes = ['platform_admin', 'community_admin', 'community_service'];
      if (!validTypes.includes(updateData.type)) {
        ctx.throw(400, '无效的客服类型');
      }
    }

    // 如果要更新状态，检查是否有效
    if (updateData.status) {
      const validStatus = ['active', 'inactive'];
      if (!validStatus.includes(updateData.status)) {
        ctx.throw(400, '无效的状态');
      }
    }

    // 如果要更新email，进行相关验证
    if (updateData.email && updateData.email !== staff.email) {
      // 检查邮箱是否已注册
      const user = await User.findOne({
        where: { email: updateData.email }
      });

      if (!user) {
        ctx.status = 400;
        ctx.body = {
          message: '该邮箱尚未注册用户账号'
        };
        return;
      }

      // 检查邮箱是否已被其他客服使用
      const existingStaff = await ServiceStaff.findOne({
        where: { email: updateData.email }
      });
      if (existingStaff) {
        ctx.throw(400, '该邮箱已被其他客服使用');
      }

      // 如果没有提供新的userId，使用新邮箱对应的用户id
      if (!updateData.userId) {
        updateData.userId = user.id;
      }
    }

    // 如果要更新userId，检查是否已被使用
    if (updateData.userId && updateData.userId !== staff.userId) {
      const existingStaffWithUserId = await ServiceStaff.findOne({
        where: { userId: updateData.userId }
      });
      if (existingStaffWithUserId) {
        ctx.throw(400, '该用户已经是其他客服了');
      }
    }

    // 更新信息
    await staff.update({
      nickname: updateData.nickname || staff.nickname,
      phone: updateData.phone || staff.phone,
      email: updateData.email || staff.email,
      userId: updateData.userId || staff.userId,
      type: updateData.type || staff.type,
      description: updateData.description || staff.description,
      status: updateData.status || staff.status
    });

    ctx.body = staff;
  } catch (error) {
    console.error('更新客服信息失败:', error);
    ctx.throw(500, '更新客服信息失败');
  }
});

// 删除客服
router.delete('/:id', async (ctx) => {
  try {
    const { id } = ctx.params;
    const staff = await ServiceStaff.findByPk(id);
    
    if (!staff) {
      ctx.throw(404, '客服不存在');
    }

    // 不允许删除默认客服
    if (['平台管理员', '社区管理员', '社区客服'].includes(staff.nickname)) {
      ctx.throw(400, '不能删除默认客服');
    }

    await staff.destroy();
    ctx.status = 204;
  } catch (error) {
    console.error('删除客服失败:', error);
    ctx.throw(500, '删除客服失败');
  }
});

// 修改客服状态
router.patch('/:id/status', async (ctx) => {
  try {
    const { id } = ctx.params;
    const { status } = ctx.request.body;

    if (!['active', 'inactive'].includes(status)) {
      ctx.throw(400, '无效的状态');
    }

    const staff = await ServiceStaff.findByPk(id);
    if (!staff) {
      ctx.throw(404, '客服不存在');
    }

    await staff.update({ status });
    ctx.body = staff;
  } catch (error) {
    console.error('更新客服状态失败:', error);
    ctx.throw(500, '更新客服状态失败');
  }
});

export default router;
